
import { arrWinner } from "../../shared/tsgf/Utils";
import { IRoomRegInfoInServer } from "../../shared/tsgfServer/room/Models";
import { RoomHelper } from "../../shared/tsgfServer/room/RoomHelper";
import { buildGuid } from "../../shared/tsgfServer/ServerUtils";
import { ReqCreateRoom, ResCreateRoom } from "../../shared/hallClient/protocols/PtlCreateRoom";
import { HallApiCall } from "../HallServer";
import { ErrorCodes } from "../../shared/tsgf/Result";

export async function ApiCreateRoom(call: HallApiCall<ReqCreateRoom, ResCreateRoom>) {
    let gameServerList = await call.getHallServer().getAllGameServers();
    let minGameServer = arrWinner(gameServerList,
        (winner, item) => winner.clientCount > item.clientCount ? item : winner);
    if (!minGameServer) {
        return await call.error('暂无可用游戏服务器！', { code: ErrorCodes.RoomNoServerAvailable });
    }
    let createInfo = RoomHelper.buildRoomInfo(call.conn.currPlayer.authInfo.appId, minGameServer.serverNodeId, call.req);
    await RoomHelper.regRoom(createInfo.regInfo, createInfo.roomInfo);

    return await call.succ({
        gameServerUrl: minGameServer.serverUrl,
        roomInfo: createInfo.roomInfo,
    });
}